package genia.controller;

import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.util.MultiValueMap;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

@Controller
public class FileProcessController {
    // 多文件上传功能实现
    @RequestMapping(path = "/uploadFiles" ,method = RequestMethod.POST, produces = "application/json")
    @ResponseBody
    public Map<String, Object> uploadFiles (HttpServletRequest request,
                                            @RequestPart("files") MultipartFile[] uploadFiles)
                                            throws IOException {

        String uploadPath = "D:\\java_Projects\\web-framework-spring\\web\\WEB-INF\\static\\files\\";
        for (MultipartFile file : uploadFiles) {
            String originalFilename = file.getOriginalFilename();
            System.out.println(originalFilename);
            file.transferTo(new File(uploadPath + originalFilename));
        }
        Map<String, Object> result = new HashMap<>();
        result.put("code", 200);
        result.put("message", "文件保存success");
        return result;
    }

    // 文件下载功能实现
    @GetMapping(path="/download")
    public ResponseEntity<byte[]> download(HttpServletRequest request,
            HttpServletResponse response, String filename) throws IOException {
            //下载时文件路径
            String uploadPath = "D:\\java_Projects\\web-framework-spring\\web\\WEB-INF\\static\\files\\";
            String filepath= uploadPath+filename;
            File file =new File(filepath);
            //借助文件输入流
            InputStream in = new FileInputStream(file);
            byte[] body = new byte[in.available()];
            in.read(body);
            //设置请求头
            MultiValueMap<String, String> headers = new HttpHeaders();
            String  fileName = new String(file.getName().getBytes("UTF-8"),"ISO-8859-1");
            headers.add("Content-Disposition", "attachment;filename=" + fileName);
            //赋值状态码
            HttpStatus statusCode = HttpStatus.OK;
            in.close();
            ResponseEntity<byte[]> entity = new ResponseEntity<byte[]>(body, headers, statusCode);
            return entity;
    }
}
